package edu.scut.luluteam.contextlib.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import edu.scut.luluteam.contextlib.collection.ContextInfoManager;
import edu.scut.luluteam.contextlib.constant.AppHolder;
import edu.scut.luluteam.contextlib.utils.LocationHelper;
import edu.scut.luluteam.contextlib.utils.ToastUtil;


/**
 * @author Guan
 */
public class LocationService extends Service {

    private static final String TAG = "LocationService";
    LocationHelper locationHelper;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "LocationService onStartCommand()");

        final String itemId = intent.getStringExtra("itemId");
        final int rating = intent.getIntExtra("rating", -1);
        final long duration = intent.getLongExtra("duration", -1);
        final int wordCount = intent.getIntExtra("wordCount", -1);

        locationHelper = LocationHelper.requestLocation(AppHolder.appContext, new LocationHelper.ResponseListener() {
            @Override
            public void onSuccessResponse(double latitude, double longitude) {
                ToastUtil.LOG_TOAST(getApplicationContext(), "纬度=" + latitude + "   longitude=" + longitude);
                ContextInfoManager.getInstance().postContextInfo(itemId, rating, duration, wordCount, latitude, longitude);
                stop();
            }

            @Override
            public void onErrorResponse(String provider, int status) {
                ToastUtil.LOG_TOAST(getApplicationContext(), "定位失败");
                stop();
            }
        });


        return super.onStartCommand(intent, flags, startId);
    }

    public void stop() {
        LocationHelper.stopLocation(locationHelper);
        stopSelf();
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "LocationService onDestroy()");
        super.onDestroy();
    }
}
